//
//  TheRedemptionPreviewViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/3/7.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "TheRedemptionPreviewViewController.h"
#import "UIViewController+CBPopup.h"
#import "EOSAccountResult.h"
#import "LeaseListViewController.h"
#import "EOSService.h"
@interface TheRedemptionPreviewViewController ()
@property (nonatomic,strong)NSArray<EOSAccountDelegatedBandwidth*>* data;
@property (nonatomic,strong) UILabel*titleInfoLab;
@property (nonatomic,strong) NSString*titleInfoStr;
@property (nonatomic,strong) EOSService*eosService;
@property (nonatomic,strong) Wallet*wallet;
@property (nonatomic,copy) void(^sureBlock)(BOOL success);

@end

@implementation TheRedemptionPreviewViewController
+ (void)alertController:(UIViewController*)controller infoDelegate:(NSArray<EOSAccountDelegatedBandwidth*>*)data withWallet:(Wallet*)wallet sureBlock:(void(^)(BOOL success))sureBlock{
    
    TheRedemptionPreviewViewController *vc = [TheRedemptionPreviewViewController new];
    vc.view.backgroundColor = UIColor.whiteColor;
    vc.data = data;
    vc.wallet = wallet;
    vc.sureBlock = sureBlock;
    vc.view.frame = CGRectMake(0, 0, AdaptedWidth(330), data.count>1?AdaptedWidth(370):AdaptedWidth(270));
    [controller cb_presentPopupViewController:vc animationType:CBPopupViewAnimationFade aligment:CBPopupViewAligmentCenter overlayDismissEnabled:YES
                             overlayDismissed:nil];
}

- (void)setData:(NSArray<EOSAccountDelegatedBandwidth *> *)data{
    _data = data;
    
   __block NSDecimalNumber *cpu = [[NSDecimalNumber alloc]initWithString:@"0"];
   __block NSDecimalNumber *net = [[NSDecimalNumber alloc]initWithString:@"0"];
    [data enumerateObjectsUsingBlock:^(EOSAccountDelegatedBandwidth * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        cpu = SNAdd(cpu, [obj.cpu_weight getDigital]);
        net = SNAdd(net, [obj.net_weight getDigital]);
    }];
    self.titleInfoStr = [NSString stringWithFormat:@"%@:%ld  %@: %@  %@: %@",XLocalized(@"赎回账号数"),data.count,XLocalized(@"计算"),[NSString stringWithFormat:@"%.*f",kSymbolLength_EOS,[cpu floatValue]],XLocalized(@"网络"),[NSString stringWithFormat:@"%.*f",kSymbolLength_EOS,[net floatValue]]];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    self.navigationBarHidden = YES;
    [super viewDidLoad];
    ViewRadius(self.view, AdaptedWidth(13));
    self.tableView.rowHeight = AdaptedWidth(100);
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView *footV = [[UIView alloc]init];
    [self.view addSubview:footV];
    footV.backgroundColor = UIColor.whiteColor;
    [footV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo( AdaptedWidth(70));
    }];
    XThemeFlatButton *bottomBtn = [XThemeFlatButton button];
    [bottomBtn setTitle:XLocalized(@"确认赎回") forState:UIControlStateNormal];
    [footV addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.bottom.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(40));
    }];
    [self.tableView registerClass:UITableViewHeaderFooterView.class forHeaderFooterViewReuseIdentifier:@"headView"];
    
    kWeakSelf(self);
    [bottomBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [XAlertTool alertTitle:XLocalized(@"确认赎回?") message:nil cancelAction:^{
            
        } sureAction:^{
           
            [weakself callBack];
            
        }];
    }];
}

- (void)callBack{
    [WalletTool checkPrivateInputPasswordWith:self.wallet complete:^(BOOL result,NSString * _Nonnull privateKey) {
        if (result) {
            [MBProgressHUD showLoadTitile:@"" ToView:self.view];
            NSMutableArray*binargsArr = [NSMutableArray array];
            self.eosService.available_keys = @[VALIDATE_STRING(self.wallet.wallet_public_key)];
            self.eosService.privateKey = privateKey;
            self.eosService.action = ContractAction_UNDELEGATEBW;
            self.eosService.account = kContractName_EOSIO;
            self.eosService.actor = self.wallet.wallet_name;
            dispatch_group_t pushGroupDispatch = dispatch_group_create();
            [self.data enumerateObjectsUsingBlock:^(EOSAccountDelegatedBandwidth * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                dispatch_group_async(pushGroupDispatch, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                    self.eosService.toUser = obj.to;
//                    DLog(@"obj.to   %@",obj.to);
//                    self.eosService.stake_cpu_quantity = obj.cpu_weight;
//                    self.eosService.stake_net_quantity = obj.net_weight;
//                    self.eosService.account = kContractName_EOSIO;
//                    self.eosService.available_keys = @[VALIDATE_STRING(self.wallet.wallet_public_key)];
//                    self.eosService.actor = self.wallet.wallet_name;
//                    self.eosService.action = ContractAction_UNDELEGATEBW;
//                    self.eosService.privateKey = privateKey;
                    [self.eosService getBlockInfoComplete:^(BOOL success, NSString *errorMsg) {
                        if (success) {
                            NSDictionary*parame = @{@"code":VALIDATE_STRING(kContractName_EOSIO),@"action":VALIDATE_STRING(self.eosService.action),@"args":@{@"from":VALIDATE_STRING(self.eosService.actor),@"receiver":VALIDATE_STRING(obj.to),@"unstake_net_quantity":VALIDATE_STRING( obj.net_weight),@"unstake_cpu_quantity":VALIDATE_STRING(obj.cpu_weight)}} ;
                            DLog(@"parame   %@",parame);

                            [self.eosService abiJsonTobinParameters:parame complete:^(BOOL success, NSString *errorMsg) {
                                if (success) {
                                    [binargsArr addObject:VALIDATE_STRING(self.eosService.binargs)];
                                    dispatch_group_leave(pushGroupDispatch);
                                }else{
                                    dispatch_group_leave(pushGroupDispatch);
                                    [self.view makeToast:errorMsg];
                                }
                            }];
                        }else{
                            dispatch_group_leave(pushGroupDispatch);
                            [self.view makeToast:errorMsg];
                        }
                    }];
                });
                dispatch_group_enter(pushGroupDispatch);
            }];
            dispatch_group_notify(pushGroupDispatch, dispatch_get_main_queue(), ^{
                if (!binargsArr.count) {
                    [MBProgressHUD hideHUDForView:self.view];
                    return;
                }
                self.eosService.binargsArr = binargsArr.copy;
                DLog(@"binargsArr == %@",binargsArr);
                [self.eosService pushTransactionComplete:^(BOOL success,BOOL executed, NSString * _Nonnull errorMsg) {
                    [MBProgressHUD hideHUDForView:self.view];
                    if (success) {
//                        if (executed) {
//                            [kAppWindow makeToast:XLocalized(@"赎回成功！")];
//                        }else{
                            [kAppWindow makeToast:XLocalized(@"交易已提交,请等待区块确认！")];
//                        }
                        [self cb_dismissPopupViewControllerAnimated:YES completion:^{
                            !self.sureBlock?:self.sureBlock(YES);
                        }];
                    }else{
                        [self.view makeToast:errorMsg];
                    }
                }];
            });
        }
    }];
}


- (void)viewWillLayoutSubviews{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.customNavigationBar.mas_bottom).offset(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(AdaptedWidth(-70));
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeaseListCell *cell = [LeaseListCell cellForTableView:tableView];
    cell.copBtn.hidden = YES;
    cell.backView.backgroundColor = UIColorHex(#F7F7F7);
    EOSAccountDelegatedBandwidth *model = [self.data objectOrNilAtIndex:indexPath.row];
    cell.nameLab.text = model.to;
    cell.cpuLab.text = [NSString stringWithFormat:@"%@:%@",XLocalized(@"计算"),model.cpu_weight];
    cell.netLab.text = [NSString stringWithFormat:@"%@:%@",XLocalized(@"网络"),model.net_weight];
    return cell;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headView"];
    UILabel *titleLab = [headV.contentView viewWithTag:1000];
    headV.contentView.backgroundColor = [UIColor whiteColor];
    if (!titleLab) {
        titleLab = [UILabel new];
        titleLab.textColor = UIColorHex(#333333);
        titleLab.font = kBoldFont(17);
        titleLab.text = XLocalized(@"赎回预览");
        [headV addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.top.mas_equalTo(AdaptedWidth(25));
        }];
    }
    if (!self.titleInfoLab) {
        self.titleInfoLab = [UILabel new];
        self.titleInfoLab.textColor = UIColorHex(#B5B5B5);
        self.titleInfoLab.font = kDefaultFont(12);
        [headV addSubview:self.titleInfoLab];
        [self.titleInfoLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(0);
            make.top.equalTo(titleLab.mas_bottom).offset(AdaptedWidth(20));
        }];
    }
    
    self.titleInfoLab.text =  self.titleInfoStr;
    return headV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return AdaptedWidth(100);
}

#pragma mark - getter

- (EOSService*)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
        _eosService.wallet = self.wallet;
    }
    return _eosService;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
